package com.abel.roommanager.interceptor;

import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class FileTypeInterceptor extends HandlerInterceptorAdapter{
  @Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
		throws Exception {
	  boolean flag=true;
	  if (request instanceof MultipartHttpServletRequest) {
		MultipartHttpServletRequest mhsr=(MultipartHttpServletRequest)request;
//		获取上传的文件
		Map<String, MultipartFile>fileMap=mhsr.getFileMap();
		if (fileMap==null) {
			return true;
		}
		Iterator<String> iterator=fileMap.keySet().iterator();
		while (iterator.hasNext()) {
			String key = (String) iterator.next();
			MultipartFile file=fileMap.get(key);
//			获取文件名
			String fileName=file.getOriginalFilename();
//			判断文件后缀名是否为指定格式
			boolean isImage=checkType(fileName);
			if (!isImage) {
				request.setAttribute("error", "文件格式错误");
				request.getRequestDispatcher("/jsp/addStu.jsp").forward(request, response);
				flag=false;
			}
		}
	}
	  
			return flag;
	
}

    private boolean checkType(String fileName) {
    	boolean flag=true;
	    int index=fileName.lastIndexOf(".");
	    String imageSuffix="jpg,jpeg,png";
	    String suffix=fileName.substring(index+1);
	    if (!imageSuffix.contains(suffix)) {
			flag=false;
		}
	return flag;
}
}
